package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.pansoft.nfc.mifare.Common;
import com.pansoft.nfc.mifare.activity.MifareDeleteColdWalletActivity;
import com.pansoft.nfc.mifare.activity.MifareNfcMessageActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.CardBean;
import com.pansoft.openplanet.bean.CardWalletInfo;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.db.CardDao;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.SelectAvatarDialog;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 卡片界面修改钱包头像跟名称的界面
 *
 * @author maming
 * @date 2019/4/28 16:20
 */
public class NewIPAssetsWalletDetailsActivity extends TCBaseActivity implements View.OnClickListener {
    //
    private RelativeLayout rlLayout1;
    private ImageView ivIcon, iv_copy;
    private TextView tvWalletName;
    private TextView tvWalletAddress;
    private RelativeLayout rlLayout2;
    private ImageView ivAvatar;
    private RelativeLayout rlLayout3;
    private TextView tvShowname;
    private Button butDelete;
    private TextView tvConvert;

    private String pictureUrlPath;//头像在网络上的位置
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
    private SelectAvatarDialog selectAvatarDialog;

    private CardBean cardBean;
    private List<CardWalletInfo> cardWalletInfos;
    private String address;
    private CardDao cardDao;
    private CardWalletInfo currentCardWalletInfo;
    private Account account;
    private AccountDao accountDao;

    public static void start(Context context, String cardNo, String address) {
        Intent starter = new Intent(context, NewIPAssetsWalletDetailsActivity.class);
        starter.putExtra("address", address);
        starter.putExtra("cardNo", cardNo);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_update_new_wallet_avatar_name);
        address = getIntent().getStringExtra("address");
        accountDao = new AccountDao(this);
        account = accountDao.getAccount(address);
        if (account == null) {
            finish();
        }
        initView();
//        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
        dismissLoading();
    }

    private void initView() {
        TextView tvName = (TextView) findViewById(R.id.tv_title);
        tvName.setText(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_management));
        rlLayout1 = (RelativeLayout) findViewById(R.id.rl_layout1);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        iv_copy = (ImageView) findViewById(R.id.iv_copy);
        tvWalletName = (TextView) findViewById(R.id.tv_wallet_name);
        tvWalletAddress = (TextView) findViewById(R.id.tv_wallet_address);
        rlLayout2 = (RelativeLayout) findViewById(R.id.rl_layout2);
        ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
        rlLayout3 = (RelativeLayout) findViewById(R.id.rl_layout3);
        tvShowname = (TextView) findViewById(R.id.tv_showname);
        butDelete = (Button) findViewById(R.id.but_delete);
        iv_copy.setOnClickListener(this);
        butDelete.setOnClickListener(this);
        rlLayout2.setOnClickListener(this);
        rlLayout3.setOnClickListener(this);
        tvConvert = (TextView) findViewById(R.id.tv_convert);
        findViewById(R.id.cl_convert).setOnClickListener(this);
    }

    private void initData() {
        pictureAndCropManager = new PictureAndCropManager(this);
        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);
        cardDao = new CardDao(this);
        cardBean = cardDao.getCardBean(getIntent().getStringExtra("cardNo"));
        cardWalletInfos = cardBean.getWalletInfoList();
        for (int i = 0; i < cardWalletInfos.size(); i++) {
            if (address.equals(cardWalletInfos.get(i).getAddress())) {
                currentCardWalletInfo = cardWalletInfos.get(i);
                break;
            }
        }
        tvWalletAddress.setText(address.replace(address.substring(6, address.length() - 4), "****"));
        tvWalletAddress.setTextColor(getResources().getColor(R.color.op_text_sub_color));
        tvShowname.setText(getDefaultWalletName(currentCardWalletInfo.getChainId()));

        if (StringUtils.isEmpty(currentCardWalletInfo.getWalletAvatar())) {
            LXGlideImageLoader.getInstance().displayRoundCornerImage(NewIPAssetsWalletDetailsActivity.this, ivAvatar,
                    R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
            LXGlideImageLoader.getInstance().displayRoundCornerImage(NewIPAssetsWalletDetailsActivity.this, ivIcon,
                    R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
        } else {
            LXGlideImageLoader.getInstance().displayRoundCornerImage(NewIPAssetsWalletDetailsActivity.this,
                    ivAvatar, currentCardWalletInfo.getWalletAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
            LXGlideImageLoader.getInstance().displayRoundCornerImage(NewIPAssetsWalletDetailsActivity.this,
                    ivIcon, currentCardWalletInfo.getWalletAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
        }
        tvConvert.setText(R.string.op_convert_to_hot_wallet);
    }

    /**
     * 根据chainId获取默认钱包名
     * @param chainId chainId
     * @return 默认钱包名
     */
    private String getDefaultWalletName(int chainId) {
        if (!StringUtils.isEmpty(currentCardWalletInfo.getWalletName())) {
            return currentCardWalletInfo.getWalletName();
        }
        switch (chainId) {
            case IPAssetsConstant.CHAIN_ID_ETH:
                return "ETH-Wallet";
            case IPAssetsConstant.CHAIN_ID_BTC:
                return "BTC-Wallet";
            default:
                return "";
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_layout2) {
            selectAvatarDialog.show();
        } else if (id == R.id.rl_layout3) {
            showNameAlert();
        } else if (id == R.id.but_delete) {
            deleteWalletDialog();
        } else if (id == R.id.cl_convert) {
            //冷热钱包转换
            //直接读取NFC
            if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                return;
            }
            // 直接读取NFC
            if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(this)) {
                MifareNfcMessageActivity.start(NewIPAssetsWalletDetailsActivity.this,
                        address, BleBlutoothScanActivity.TYPE_CONVERT_WALLET);
            } else {
//                //蓝牙读卡器
                BleBlutoothScanActivity.start(NewIPAssetsWalletDetailsActivity.this,
                        account.getAddress(), BleBlutoothScanActivity.TYPE_CONVERT_WALLET,
                        BleBlutoothScanActivity.BLE_TYPE_NFC);
            }
        } else if (id == R.id.iv_copy) {
            //复制地址
            copyAddress(address);
        }
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission() && selectAvatarDialog != null) {
            selectAvatarDialog.startTakePhoto();
        }
    }

    //删除钱包
    private void deleteWalletDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_remove_wallet))
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent;
                        if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                            return;
                        }
                        // 直接读取NFC
                        if (!EnvSupportManager.isSupportForceBleNfc() &&
                                Common.hasMifareClassicSupport(NewIPAssetsWalletDetailsActivity.this)) {
                            intent = new Intent(NewIPAssetsWalletDetailsActivity.this, MifareDeleteColdWalletActivity.class);
                        } else {
                            intent = new Intent(NewIPAssetsWalletDetailsActivity.this, BleBlutoothScanActivity.class);
                            intent.putExtra("createType", BleBlutoothScanActivity.TYPE_DELETE_COLD_CHILD_WALLET);
                            intent.putExtra("bleDeviceType", BleBlutoothScanActivity.BLE_TYPE_NFC);
                        }
                        intent.putExtra("address", address);
                        intent.putExtra("cardNo", cardBean.getUid());
                        startActivityForResult(intent, 6656);
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null).show();
    }

    //名称修改
    private void showNameAlert() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                com.efounder.chat.R.layout.social_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = layout
                .findViewById(com.efounder.chat.R.id.ed_name);
        ed_name.setText(currentCardWalletInfo.getWalletName());
        ed_name.setSelection(ed_name.getText().length());
        dialog.setTitle(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_enter_wallet_name));
        dialog.setPositiveButton(R.string.common_text_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String newName = ed_name.getText().toString().trim();
                        if (TextUtils.isEmpty(newName)) {
                            return;
                        } else {
                            //调用接口
                            if (account == null) {
                                updateCardWalletName(newName);
                                ToastUtil.showToast(NewIPAssetsWalletDetailsActivity.this, ResStringUtil.getString(R.string.open_planet_change_success));
                                return;
                            }
                            updateWalletInfo("accountName", newName);
                        }
                        dialog.cancel();
                    }
                });
        dialog.setNegativeButton(R.string.common_text_cancel, null);
        dialog.show();
    }

    /**
     * 更新本地卡片数据库钱包名
     * @param newName
     */
    private void updateCardWalletName(String newName) {
        tvShowname.setText(newName);
        //只更新card数据库
        currentCardWalletInfo.setWalletName(newName);
        cardBean.setWalletInfoList(cardWalletInfos);
        cardDao.insertOrReplace(cardBean);
    }

    /**
     * 更新本地卡片数据库钱包头像
     */
    private void updateCardWalletAvatar(String avatar) {
        LXGlideImageLoader.getInstance().displayRoundCornerImage(NewIPAssetsWalletDetailsActivity.this,
                ivAvatar, pictureUrlPath, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
        //只更新card数据库
        currentCardWalletInfo.setWalletAvatar(avatar);
        cardBean.setWalletInfoList(cardWalletInfos);
        cardDao.insertOrReplace(cardBean);
    }

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(Uri.fromFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    }
                    break;

                case PHOTO_REQUEST_CUT:
                    if (!isNetActive()) {
                        ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.common_text_network_error_please_again));
                        return;
                    }
                    showLoading(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_uploading_avatar));
                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                dismissLoading();
                                if (isSuccess) {
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    updateWalletInfo("accountIcon", pictureUrlPath);
                                } else {
                                    ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.common_text_upload_fail_again));
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 6656:
                    finish();
                    break;
                default:
                    break;

            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 修改头像或名称
     */
    private void updateWalletInfo(final String key, final String value) {
        if (account == null) {
            updateCardWalletAvatar(value);
            ToastUtil.showToast(NewIPAssetsWalletDetailsActivity.this, ResStringUtil.getString(R.string.open_planet_change_success));
            return;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(key, value);
        hashMap.put("accountAddress", account.getAddress());
        hashMap.put("mainAccountAddress", account.getMainAccoutAddress());
        if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)) {
            hashMap.put("blockChainName", "BTC");
        }
        TCRequestUtil.getCommonRequest(TAG, "account/updateChildrenWallet", hashMap,
                new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if (jsonObject.optString("result", "").equals("success")) {
                        if (key.equals("accountName")) {
//                            tvShowname.setText(value);
                            updateCardWalletName(value);
                            account.setAcccountName(value);
                            accountDao.insertOrReplace(account);
                        } else {
                            updateCardWalletAvatar(value);
                            account.setAccountAvatar(value);
                            accountDao.insertOrReplace(account);
                        }
                        ToastUtil.showToast(NewIPAssetsWalletDetailsActivity.this, ResStringUtil.getString(R.string.open_planet_change_success));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(NewIPAssetsWalletDetailsActivity.this, ResStringUtil.getString(R.string.open_planet_change_fail));
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(NewIPAssetsWalletDetailsActivity.this, ResStringUtil.getString(R.string.open_planet_change_fail));
            }
        });
    }


    /**
     * 复制地址
     *
     * @param address 地址
     */
    private void copyAddress(String address) {
        //复制账号
        ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(address);
        ToastUtils.setBgColor(this.getResources().getColor(R.color.black));
        ToastUtils.setMsgColor(this.getResources().getColor(R.color.op_text_white_color));
        ToastUtils.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 150);
        ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_child_wallet_list_copied_clipboard));
    }

}
